package com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.entity.OrdernoticeView;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.entity.SalesDelivery.SalesDelivery;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.entity.SalesDelivery.SalesDeliveryDetails;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.entity.ServiceList;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.mapper.GuiZeMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.mapper.ServiceListMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderNoticeEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.service.RePickService;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.StorerecordEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.StorerecordEntityMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.utils.GenericResponse;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class GuiZeService {
    private static final Logger logger = LoggerFactory.getLogger(GuiZeService.class);

    @Autowired
    GuiZeMapperImpl guizeMapper;
    @Autowired
    BaseService baseService;
    @Autowired
    RePickService rePickService;

    @Autowired
    ServiceListMapperImpl serviceListMapper;

    @Autowired
    StorerecordEntityMapperImpl tempStorerecordEntityMapper;

    @Transactional(rollbackFor = Exception.class)
    public DataResult InsertorUpdateordernotice(List<OrderNoticeEntity> ordernoticeList, String tenantId, String ordertype) {
        DataResult dataResult = null;
        try {
            if (ordernoticeList != null && ordernoticeList.size() > 0) {
                for (int i = 0; i < ordernoticeList.size(); i++) {
                    String orderid = ordernoticeList.get(i).getOrderid();
                    OrderNoticeEntity ordernoticeEntry = guizeMapper.selectOrdernoticeEntity(orderid, ordertype, tenantId);
                    if (ordernoticeEntry != null) {
                        guizeMapper.UpdateordernoticeList(ordernoticeList.get(i).getActioncode(),
                                ordernoticeList.get(i).getAuditstatus(),
                                ordernoticeList.get(i).getOrderid(), ordertype,
                                tenantId, ordernoticeList.get(i).getCreator(),
                                ordernoticeList.get(i).getRepickstatus());

                    } else {
                        guizeMapper.InsertordernoticeList(ordernoticeList.get(i).getType(),
                                ordernoticeList.get(i).getActioncode(), ordernoticeList.get(i).getTranstype(),
                                ordernoticeList.get(i).getOrderid(), ordernoticeList.get(i).getOrdercode(),
                                ordernoticeList.get(i).getOrderdetailids(), ordernoticeList.get(i).getSourceid(),
                                ordernoticeList.get(i).getSourcecode(), ordernoticeList.get(i).getSourcedetailids(),
                                ordernoticeList.get(i).getFirstsourceid(),
                                ordernoticeList.get(i).getFirstsourcecode(),
                                ordernoticeList.get(i).getFirstsourcedetailids(), tenantId,
                                ordernoticeList.get(i).getCreator(), ordernoticeList.get(i).getAuditstatus(),
                                ordernoticeList.get(i).getRepickstatus());
                    }
                }
                dataResult = new DataResult(1, "数据状态更新成功！");
            } else {
                dataResult = new DataResult(0, "数据状态更新条数0！");
            }
        } catch (Exception e) {
            //e.printStackTrace();
            dataResult = new DataResult(0, "数据状态更新失败！" + e);
            return dataResult;
        }

        return dataResult;
    }

    @Transactional(rollbackFor = Exception.class)
    public DataResult Saveordernotice(OrdernoticeView ordernotice, String ordertype, String tenantId) {
        DataResult dataResult = new DataResult(0, "操作失败");
        if (ordernotice == null || StringUtils.isEmpty(ordernotice.getOrderArr())) {
            dataResult = new DataResult(0, "数据状态更新条数0！");
            return dataResult;
        }
        String[] orderarr = ordernotice.getOrderArr().split(",");
        if (orderarr == null || orderarr.length == 0) {
            dataResult = new DataResult(0, "数据状态更新条数0！");
            return dataResult;
        }
        try {
            String myMessage = "";
            for (int i = 0; i < orderarr.length; i++) {
                String[] orderiden = orderarr[i].split("\\|");
                String transtypeName = "";
                if (orderiden.length > 2) {
                    transtypeName = orderiden[2];
                }
                String orderid = orderiden[0];
                String ordercode = orderiden[3];
                // 弃审判断
                if (ordernotice.getAuditstatus() == 2) {
                    List<StorerecordEntity> storerecordBeans = tempStorerecordEntityMapper.selectListByOrdertype(orderid, ordertype, ordernotice.getTenantId());
                    if (storerecordBeans.size() > 0) {
                        myMessage += ", " + ordercode;
                        myMessage = "操作失败，单号：" + myMessage.substring(1);
                        dataResult = new DataResult(0, "数据状态更新成功！");
                        dataResult.setMessage(myMessage);
                        return dataResult;
                    }
                }
                OrderNoticeEntity ordernoticeEntity = guizeMapper.selectOrdernoticeEntity(orderiden[0], ordertype, tenantId);
                if (ordernoticeEntity != null) {
                    guizeMapper.Updateordernotice(ordernotice.getActioncode(), transtypeName,
                            ordernotice.getAuditstatus(), ordernoticeEntity.getId().toString(),
                            ordernotice.getTenantId(), ordernotice.getUpdateor());

                } else {
                    guizeMapper.Insertordernotice(3, ordernotice.getActioncode(), transtypeName, orderiden[0]
                            , orderiden[3],
                            "", "", "", "", "",
                            "", "", ordernotice.getTenantId(), ordernotice.getUpdateor(),
                            ordernotice.getAuditstatus(), 0);
                }
            }
            // 更新提醒信息
            if (!StringUtils.isEmpty(myMessage) && myMessage.length() > 1) {
                myMessage = "操作失败，单号：" + myMessage.substring(1);
            }
            dataResult = new DataResult(1, "数据状态更新成功！");
            dataResult.setMessage(myMessage);
        } catch (Exception e) {
            //e.printStackTrace();
            dataResult = new DataResult(0, "数据状态更新失败！" + e);
            return dataResult;
        }

        return dataResult;
    }

    /**
     * 发货单 单据弃审的操作
     * 包含反捡货物资的插入
     *
     * @param idsString id
     * @return 返回插入结果
     */
    public DataResult SalesDeliveryAbandonAudit(String idsString, String tenantId) throws Exception {
        DataResult dataResult = new DataResult(0, "插入失败");
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);

        String ordertype = "2"; //发货单
        String url = gatewayUrl + ApiYon.getOutListDetail;

        if (idsString != null && idsString.length() > 0) {
            List<String> ids = MyTool.StringRemoveLastSymbolToList(idsString, ",");
            ids = ids.stream().distinct().collect(Collectors.toList()); // 祛除重复的内容
            // 循环访问单据内容
            for (String item : ids) {
                Map<String, String> params = new HashMap<>();
                params.put("id", item);
                params.put("access_token", token);
                String resString = RequestTool.doGet(url, params);
                GenericResponse<SalesDelivery> response = RequestTool.getBean(resString,
                        new TypeReference<GenericResponse<SalesDelivery>>() {
                        });

                if (response.getCode().equals("200")) {
                    List<OrderNoticeEntity> ordernoticeList = new ArrayList<>(); // 需要插入或者更新的单据信息
                    // 内容进行翻译
                    SalesDelivery salesDelivery = response.getData();
                    String detailIds = salesDelivery.getDeliveryDetails().stream().map(it -> it.getId()).distinct().collect(Collectors.joining(","));
                    // 单据状态表的信息写入
                    OrderNoticeEntity ordernotice = new OrderNoticeEntity();
                    ordernotice.setSourceid(salesDelivery.getOrderId());
                    ordernotice.setOrderid(salesDelivery.getId());
                    ordernotice.setOrdercode(salesDelivery.getCode());
                    ordernotice.setType(2);
                    ordernotice.setOrderdetailids(detailIds);
                    ordernotice.setTranstype(salesDelivery.getTransactionTypeId_name());
                    ordernotice.setActioncode("unpick");
                    ordernotice.setCreator(salesDelivery.getCreator());
                    ordernotice.setAuditstatus(2);
                    ordernotice.setRepickstatus(0);
                    ordernoticeList.add(ordernotice);
                    DataResult dataResult1 = InsertorUpdateordernotice(ordernoticeList, tenantId, ordertype);
                    if (dataResult1.getStatus() == 1) {
                        // 单条数据的插入
                        if (salesDelivery.getDeliveryDetails().size() > 0) {
                            int orderDetailCount = rePickService.InsertStoreRecodeByOrderIdAndPId(tenantId,
                                    salesDelivery, salesDelivery.getDeliveryDetails());
                            dataResult.setData(orderDetailCount);
                        }
                    } else {
                        return dataResult;
                    }
                } else {
                    dataResult.setMessage("未获取到相关信息，请检查数据。原因：" + response.getMessage());
                    return dataResult;
                }
            }
            dataResult.setStatus(1);
            dataResult.setMessage("提交成功");
        } else {
            dataResult.setMessage("提交数据有误，请重新检查");
        }
        return dataResult;
    }

    /**
     * 单据审核接口
     *
     * @param idsString 审核的单据Id
     * @return 返回结果
     */
    public DataResult SalesDeliveryAudit(String idsString, String tenantId, int flagaudit) throws Exception {
        DataResult dataResult = new DataResult(0, "插入失败");
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);

        String ordertype = "2"; //发货单
        String url = gatewayUrl + ApiYon.getOutListDetail;

        if (idsString != null && idsString.length() > 0) {
            List<String> ids = MyTool.StringRemoveLastSymbolToList(idsString, ",");
            ids = ids.stream().distinct().collect(Collectors.toList()); // 祛除重复的内容
            // 循环访问单据内容
            for (String item : ids) {
                Map<String, String> params = new HashMap<>();
                params.put("id", item);
                params.put("access_token", token);
                String resString = RequestTool.doGet(url, params);
                GenericResponse<SalesDelivery> response = RequestTool.getBean(resString,
                        new TypeReference<GenericResponse<SalesDelivery>>() {
                        });

                if (response.getCode().equals("200")) {
                    List<OrderNoticeEntity> ordernoticeList = new ArrayList<>(); // 需要插入或者更新的单据信息
                    // 内容进行翻译
                    SalesDelivery salesDelivery = response.getData();
                    String detailIds = salesDelivery.getDeliveryDetails().stream().map(it -> it.getId()).distinct().collect(Collectors.joining(","));
                    String whIds = salesDelivery.getDeliveryDetails().stream().map(it -> it.getStockId()).distinct().collect(Collectors.joining(","));
                    // 单据状态表的信息写入
                    OrderNoticeEntity ordernotice = new OrderNoticeEntity();
                    ordernotice.setSourceid(salesDelivery.getOrderId());
                    ordernotice.setOrderid(salesDelivery.getId());
                    ordernotice.setOrdercode(salesDelivery.getCode());
                    ordernotice.setType(2);
                    ordernotice.setOrderdetailids(detailIds);
                    ordernotice.setTranstype(salesDelivery.getTransactionTypeId_name());
                    ordernotice.setActioncode("pick");
                    ordernotice.setRemarkdxq(whIds);
                    ordernotice.setRemarkyonyou(JSONObject.toJSONString(salesDelivery));
                    ordernotice.setActioncode(salesDelivery.getTransactionTypeId());
                    ordernotice.setCreator(salesDelivery.getCreator());
                    ordernotice.setAuditstatus(1);
                    ordernotice.setRepickstatus(0);
                    ordernoticeList.add(ordernotice);
                    DataResult dataResult1 = InsertorUpdateordernotice(ordernoticeList, tenantId, ordertype);
                    if (dataResult1.getStatus() == 1) {
                        //判断是否指派仓库
                        if (flagaudit == 1) {
                            List<SalesDeliveryDetails> tempList = salesDelivery.getDeliveryDetails();
                            long checkNum =
                                    tempList.stream().filter(it -> it.getStockId() == null || it.getStockId().length() == 0).count();
                            if (checkNum > 0) {
                                dataResult.setMessage("部分物料未分配拣货仓库");
                                return dataResult;
                            }
                        }
                        // 单条数据的插入
                        if (salesDelivery.getDeliveryDetails().size() > 0) {
                            int orderDetailCount = rePickService.UpdateRepickDrStatus(salesDelivery.getId(), tenantId);
                        }
                    } else {
                        return dataResult;
                    }
                } else {
                    dataResult.setMessage("未获取到相关信息，请检查数据");
                }
            }
            dataResult.setStatus(1);
            dataResult.setMessage("提交成功");
        } else {
            dataResult.setMessage("提交数据有误，请重新检查");
        }
        return dataResult;
    }


    /**
     * 查询单据弃审状态
     *
     * @param orderid   单据Id
     * @param ordertype 单据类型
     * @return 返回单据弃审状态
     */
    public DataResult SelectOrderAuditStatus(String orderid, String ordertype) {
        DataResult dataResult = new DataResult(1, "查询成功");
        OrderNoticeEntity ordernotice = guizeMapper.selectOrderNoticeByIdAndType(orderid, ordertype);
        if (ordernotice != null) {
            dataResult.setOrderAuditType(ordernotice.getAuditstatus());
        }
        return dataResult;
    }

    /**
     * 重新获取应用列表
     *
     * @param appCode
     * @param tenantId
     * @return
     * @throws IOException
     */
    public DataResult Getlistbyappcode(String appCode, String tenantId) throws IOException {
        DataResult dataResult = new DataResult(1, "保存成功");
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);

        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("access_token", token);
        params.put("appCode", appCode);
        // 请求
        String requestUrl = gatewayUrl + ApiYon.getAppcode;
        GenericResponse<List<ServiceList>> response = RequestTool.doGet(requestUrl, params,
                new TypeReference<GenericResponse<List<ServiceList>>>() {
                });
        if (response.getCode().equals("200")) {
            List<ServiceList> serviceLists = response.getData();
            if (response.getData() != null) {
                int del = serviceListMapper.deleteservicelist();
                if (del > 0) {
                    for (int i = 0; i < serviceLists.size(); i++) {
                        ServiceList serviceentry = serviceLists.get(i);
                        serviceListMapper.Insertservicelist(serviceentry.getTenantId(),
                                serviceentry.getApplicationId(), serviceentry.getServiceId(),
                                serviceentry.getServiceName(),
                                serviceentry.getServiceCode(), serviceentry.getEnable(), serviceentry.getUrl(),
                                serviceentry.getServiceIcon(), serviceentry.getCapable(), serviceentry.getYkjId(),
                                serviceentry.getClientStatus(), serviceentry.getWebStatus(),
                                serviceentry.getPhoneStatus(), serviceentry.getStrategy(), serviceentry.getHasWidget());
                    }
                }

            }
            return dataResult;
        }
        throw new RuntimeException("请求开放平台接口失败, code: " + response.getCode() + ", message: " + response.getMessage());
    }

    public DataResult GetmainOrgPermission(String userId, String serviceCode, String tenantId) {
        DataResult dataResult = new DataResult(1, "查询成功");
        try {
            AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
            String token = MyToken.getAccessToken();
            String gatewayUrl = baseService.buildBusinessUrl(tenantId);

            Map<String, String> params = new HashMap<>();
            // 除签名外的其他参数
            params.put("userId", userId);
            params.put("serviceCode", serviceCode);
            params.put("tenantId", tenantId);
            // 请求
            String requestUrl = gatewayUrl + ApiYon.getPermission + "?access_token=" + token;
            String resString = RequestTool.doPost(requestUrl, JSON.toJSONString(params));
            JSONObject jsonObject = JSONObject.parseObject(resString);
            if (jsonObject.getString("code").equals("200")) {
                dataResult.setData(jsonObject.getString("data"));
            }
        } catch (Exception e) {
            dataResult = new DataResult(0, "查询失败！");
        }
        return dataResult;
    }


}
